package com.sicau.socialpracticesystem.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsUtils;

import javax.annotation.Resource;

import static com.sicau.socialpracticesystem.common.constant.UrlConstants.USER_PREFIX;


/**
 * @author sxt
 * @version : 1.0.0
 */
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@Order(SecurityProperties.BASIC_AUTH_ORDER)
public class MSecurityConfig extends WebSecurityConfigurerAdapter {


    @Resource
    private SecurityHandler securityHandler;

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private MPasswordEncoder mPasswordEncoder;

    /**
     * 此处给AuthenticationManager添加登陆验证的逻辑。
     * 这里添加了两个AuthenticationProvider分别用于用户名密码登陆的验证以及token授权登陆两种方式。
     * 在处理登陆信息的过滤器执行的时候会调用这两个provider进行登陆验证。
     */
    @Autowired
    public void configGlobal(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(customAuthenticationProvider())
                .eraseCredentials(true);
    }

    //用户名和密码登陆处理
    public CustomAuthenticationProvider customAuthenticationProvider() {
        return new CustomAuthenticationProvider(userDetailsService, mPasswordEncoder);
    }

    public CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
        CustomAuthenticationFilter filter = new CustomAuthenticationFilter(securityHandler);
        filter.setAuthenticationManager(authenticationManager());
        return filter;
    }

    private TokenAuthenticationFilter tokenAuthenticationFilter() {
        return new TokenAuthenticationFilter(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest)
                .permitAll()
                .antMatchers(
                        "/v2/**",
                        "/swagger-ui.html#!/**",
                        "/swagger-ui.html#/**",
                        "/swagger-ui.html/**",
                        "/swagger-resources/**",
                        "/webjars/**",
                        "/loginPage/**",
                        "/doc.html",
                        "/v1/**"
                ).permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .addFilterBefore(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .formLogin()
                .and()
                .cors()
                .and()
                .csrf().disable() //关闭CSRF
//                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .formLogin().loginPage(USER_PREFIX + "/authentication/require")
//                .loginProcessingUrl("/login")
//                .successHandler(securityHandler)
////                .successForwardUrl(USER_PREFIX + "/loginSuccess") //成功登陆后
//                .failureUrl(USER_PREFIX + "/loginError").permitAll()
                .and()
                .logout().logoutUrl("/logout")
                .logoutSuccessHandler(securityHandler)
                .and()
                //配置没有权限的自定义处理类
                .exceptionHandling().accessDeniedHandler(securityHandler); /*设置全局异常捕获后不会生效*/

    }


}
